package com.example.springboot.service;

import com.example.springboot.entity.SelfServiceOrder;
import com.example.springboot.mapper.SelfServiceOrderMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class SelfServiceOrderService {

    private static final Logger logger = LoggerFactory.getLogger(SelfServiceOrderService.class);

    @Autowired
    private SelfServiceOrderMapper selfServiceOrderMapper;

    public List<SelfServiceOrder> findAll(int page, int size, String role, String username, String status, String orderType) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        int offset = (page - 1) * size;
        if (offset < 0) {
            logger.warn("Invalid page number: {}, setting offset to 0", page);
            offset = 0;
        }
        if (size <= 0) {
            logger.warn("Invalid size: {}, defaulting to 10", size);
            size = 10;
        }

        logger.info("Fetching self-service orders for role: {}, username: {}, page: {}, size: {}, status: {}, orderType: {}",
                role, decodedUsername, page, size, status, orderType);

        try {
            String adminRole = selfServiceOrderMapper.findAdminRoleByUsername(decodedUsername);
            if (adminRole == null) {
                logger.error("No role found for username: {}", decodedUsername);
                throw new IllegalArgumentException("管理员用户不存在或角色未定义");
            }

            if ("super".equals(adminRole)) {
                logger.info("Super admin access: retrieving all self-service orders");
                List<SelfServiceOrder> orders = selfServiceOrderMapper.findAll(offset, size, status, orderType);
                logger.info("Retrieved {} self-service orders for super admin", orders.size());
                return orders;
            }

            // 普通管理员或非 ADMIN 角色
            Integer adminId = getAdminId(decodedUsername);
            logger.info("Admin access: retrieving orders for adminId: {}", adminId);
            List<SelfServiceOrder> orders = selfServiceOrderMapper.findByAdminId(offset, size, adminId, status, orderType);
            logger.info("Retrieved {} self-service orders for adminId: {}", orders.size(), adminId);
            return orders;

        } catch (Exception e) {
            logger.error("Failed to fetch self-service orders for page: {}, size: {}, role: {}, username: {}", page, size, role, decodedUsername, e);
            throw new RuntimeException("获取自助点订单列表失败: " + e.getMessage(), e);
        }
    }

    public int getTotalOrders(String role, String username, String status, String orderType) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        try {
            String adminRole = selfServiceOrderMapper.findAdminRoleByUsername(decodedUsername);
            if (adminRole == null) {
                logger.error("No role found for username: {}", decodedUsername);
                throw new IllegalArgumentException("管理员用户不存在或角色未定义");
            }

            if ("super".equals(adminRole)) {
                logger.info("Super admin access: retrieving total count of all self-service orders");
                int total = selfServiceOrderMapper.getTotalOrders(status, orderType);
                logger.info("Total self-service orders for super admin: {}", total);
                return total;
            }

            // 普通管理员或非 ADMIN 角色
            Integer adminId = getAdminId(decodedUsername);
            logger.info("Admin access: retrieving total orders for adminId: {}", adminId);
            int total = selfServiceOrderMapper.getTotalOrdersByAdminId(adminId, status, orderType);
            logger.info("Total self-service orders for adminId: {}", total);
            return total;

        } catch (Exception e) {
            logger.error("Failed to get total self-service orders for role: {}, username: {}", role, decodedUsername, e);
            throw new RuntimeException("获取自助点订单总数失败: " + e.getMessage(), e);
        }
    }

    public SelfServiceOrder findById(Integer orderId, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        SelfServiceOrder order = selfServiceOrderMapper.findById(orderId);
        if (order == null) {
            logger.warn("Self-service order not found for orderId: {}", orderId);
            throw new IllegalArgumentException("订单不存在");
        }

        String adminRole = selfServiceOrderMapper.findAdminRoleByUsername(decodedUsername);
        if ("common".equals(adminRole)) {
            Integer adminId = getAdminId(decodedUsername);
            if (!selfServiceOrderMapper.isOrderManagedByAdmin(orderId, adminId)) {
                logger.warn("Permission denied for username: {} to view self-service orderId: {}", decodedUsername, orderId);
                throw new IllegalArgumentException("无权限查看该订单");
            }
        }
        return order;
    }

    public void deleteById(Integer orderId, String role, String username) {
        String decodedUsername = decodeUsername(username);
        validateInput(role, decodedUsername);

        SelfServiceOrder order = selfServiceOrderMapper.findById(orderId);
        if (order == null) {
            logger.warn("Self-service order not found for orderId: {}", orderId);
            throw new IllegalArgumentException("订单不存在");
        }

        String adminRole = selfServiceOrderMapper.findAdminRoleByUsername(decodedUsername);
        if ("common".equals(adminRole)) {
            Integer adminId = getAdminId(decodedUsername);
            if (!selfServiceOrderMapper.isOrderManagedByAdmin(orderId, adminId)) {
                logger.warn("Permission denied for username: {} to delete self-service orderId: {}", decodedUsername, orderId);
                throw new IllegalArgumentException("无权限删除该订单");
            }
        }

        try {
            selfServiceOrderMapper.deleteById(orderId);
        } catch (Exception e) {
            logger.error("Failed to delete self-service orderId: {} for role: {}, username: {}", orderId, role, decodedUsername, e);
            throw new RuntimeException("删除自助点订单失败: " + e.getMessage(), e);
        }
    }

    private void validateInput(String role, String username) {
        if (username == null || username.trim().isEmpty()) {
            logger.error("Username is null or empty");
            throw new IllegalArgumentException("Username header is required");
        }
        if (role == null || role.trim().isEmpty()) {
            logger.error("Role is null or empty");
            throw new IllegalArgumentException("Role header is required");
        }
    }

    private Integer getAdminId(String username) {
        Integer adminId = selfServiceOrderMapper.findAdminIdByUsername(username);
        if (adminId == null) {
            logger.error("No admin ID found for username: {}", username);
            throw new IllegalArgumentException("无法获取管理员 ID，用户名可能不存在");
        }
        return adminId;
    }

    private String decodeUsername(String username) {
        if (username == null) {
            return null;
        }
        try {
            return URLDecoder.decode(username, StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            logger.warn("Failed to decode username: {}, using original value", username, e);
            return username;
        }
    }
}